getParameter = function(url, parameter, def) {
  var ret = def;

  if (url.indexOf(parameter) !== -1) {
    ret = url.split(parameter)[1].split('&');
    if (!!ret[0].split('=')[0]) {
      ret = def;
    } else {
      ret = ret[0].split('=')[1];
    }
  }

  return ret;
}

getObjectFromLocation = function(index) {
  var loc = window.location.search.replace("?","");

  var object = {
    delay: getParameter(loc, 'delay'+index, 0),
    duration: getParameter(loc, 'duration'+index, 500),
    definedTiming: getParameter(loc, 'definedTiming'+index, 'Linear'),
    customTiming: getParameter(loc, 'customTiming'+index, ''),
    initialScale: getParameter(loc, 'initialScale'+index, 0),
    initialRotate: getParameter(loc, 'initialRotate'+index, 0),
    initialOpacity: getParameter(loc, 'initialOpacity'+index, 1),
    endScale: getParameter(loc, 'endScale'+index, 1),
    endRotate: getParameter(loc, 'endRotate'+index, 0),
    endOpacity: getParameter(loc, 'endOpacity'+index, 1)
  }

  return object;
}

window.onload = function() {
  /*** JS TRANSFORMS ***/
  //META FOR MEDIA-SCREEN 
  var viewPortTag=document.createElement('meta');
  viewPortTag.id="viewport";
  viewPortTag.name = "viewport";
  viewPortTag.content = "width=device-width, initial-scale=1, maximum-scale=1";
  document.getElementsByTagName('head')[0].appendChild(viewPortTag);

  //TRANSITIONS
  var stamps_transform = styleSupport( "transform" );

  var stamps_transition = styleSupport( "transition" ),
    stamps_duration = stamps_transition+'-duration',
    stamps_timing = stamps_transition+'-timing-function',
    stamps_delay = stamps_transition+'-delay';;

  function styleSupport( prop ) {
    var vendorProp, supportedProp,
    capProp = prop.charAt(0).toUpperCase() + prop.slice(1),
    prefixes = [ "Moz", "Webkit", "O", "ms" ],
    newprefixes = [ "-moz-", "-webkit-", "-o-", "-ms-" ],
    div = document.createElement( "div" );

    if ( prop in div.style ) {
      supportedProp = prop;
    } else {
      for ( var i = 0; i < prefixes.length; i++ ) {
        vendorProp = prefixes[i] + capProp;
        if ( vendorProp in div.style ) {
          supportedProp = newprefixes[i]+prop;
          break;
        }
      }
    }

    div = null;
    return supportedProp;
  }

  var propDefTiming = { Linear: 'linear', Ease: 'ease', EaseIn: 'ease-in',
    EaseOut: 'ease-out', EaseInOut: 'ease-in-out', 
    CristoBezier: 'cubic-bezier(1,-0.22,0,1.12)',
    Quantum1: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
    Quantum2: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
    Quantum3: 'cubic-bezier(0.4, 0.0, 1, 1)'};

  var getPropFromValueDefTiming = function(value) {
    var res;
    for (var prop in propDefTiming) {
      if (propDefTiming[prop] === value) {
        res = prop;
      }
    }
    return res;
  }

  setDuration = function(the, time) {
    the.style[stamps_duration] = time+'ms';
  }

  getDuration = function(the) {
    return the.style[stamps_duration];
  }

  setTiming = function(the,timing) {
    the.style[stamps_timing] = timing;
  }

  getTiming = function(the) {
    return the.style[stamps_timing];
  }

  setDelay = function(the,delay) {
    the.style[stamps_delay] = delay+'ms';
  }

  getDelay = function(the) {
    return the.style[stamps_delay];
  }

  setTransform = function(the,scale,rotate) {
    var value = scale != undefined ? 'scale('+scale+') ' : '';
    value += rotate != undefined ? 'rotate('+rotate+'deg)' : '';
    the.style[stamps_transform] = value;
  }
  //END


  var Stamp = function(element,id) {
    var parameters = getObjectFromLocation(id);
    this.element = element;
    this.delay = parseInt(parameters.delay);
    this.duration = parseInt(parameters.duration);
    this.definedTiming = parameters.definedTiming;
    this.customTiming = parameters.customTiming;
    this.testStamp = function(){};
    this.initialScale = parseInt(parameters.initialScale);
    this.endScale = parseInt(parameters.endScale);
    this.initialRotate = parseInt(parameters.initialRotate);
    this.endRotate = parseInt(parameters.endRotate);
    this.initialOpacity = parseInt(parameters.initialOpacity);
    this.endOpacity = parseInt(parameters.endOpacity);
    this.isAnimated = false;

    this.setDuration = function(time) {
      setDuration(this.element,time);
    }

    this.getDuration = function() {
      return getDuration(this.element);
    }

    this.getDurationFromParameter = function() {
      return this.duration;
    }

    this.setTiming = function(timing) {
      this.definedTiming = getPropFromValueDefTiming(timing);
      setTiming(this.element,timing);
    }

    this.getTiming = function() {
      return getTiming(this.element);
    }

    this.getDefinedTimingFromParameter = function() {
      return this.definedTiming;
    }

    this.getCustomTimingFromParameter = function() {
      return this.customTiming;
    }

    this.setDelay = function(delay) {
      this.delay = delay;
    }

    this.getDelay = function() {
      return this.delay;
    }

    this.getDelayFromParameter = function() {
      return this.delay;
    }

    this.setOpacity = function(opacity) {
       this.element.style.opacity = opacity;
    }

    this.getOpacity = function() {
      return this.element.style.opacity;
    }

    this.getOpacityFromParameter = function() {
      return this.opacity;
    }

    this.setTransform = function(type) {
      var cScale = this.initialScale, cRotate = this.initialRotate;

      if (!!type && type === 'end') {
        cScale = this.endScale;
        cRotate = this.endRotate;
      }
      setTransform(this.element,cScale,cRotate);
    }

    this.resetScale = function(scale) {
      this.initialScale = scale;
    }

    this.resetRotate = function(rotate) {
      this.initialRotate = rotate;
    }

    this.resetOpacity = function(opacity) {
      this.initialOpacity = opacity;
    }

    this.setInitialScale = function(scale) {
      this.initialScale = scale;
      this.setTransform();
    }

    this.getInitialScaleFromParameter = function() {
      return this.initialScale;
    }

    this.setInitialRotate = function(rotate) {
      this.initialRotate = rotate;
      this.setTransform();
    }

    this.getInitialRotateFromParameter = function() {
      return this.initialRotate;
    }

    this.setInitialOpacity = function(opacity) {
      this.initialOpacity = opacity;
      this.setOpacity(opacity);
    }

    this.getInitialOpacityFromParameter = function() {
      return this.initialOpacity;
    }

    this.setEndScale = function(scale) {
      this.endScale = scale;
      this.setTransform('end');
    }

    this.getEndScaleFromParameter = function() {
      return this.endScale;
    }

    this.setEndRotate = function(rotate) {
      this.endRotate = rotate;
      this.setTransform('end');
    }

    this.getEndRotateFromParameter = function() {
      return this.endRotate;
    }

    this.setEndOpacity = function(opacity) {
      this.endOpacity = opacity;
      this.setOpacity(opacity);
    }

    this.getEndOpacityFromParameter = function() {
      return this.endOpacity;
    }

    this.start = function() {
      var obj = this;
      obj.isAnimated = true;
      var duration = obj.getDuration();
      duration = parseFloat(duration);
      var startTime = obj.getDelay();
      startTime = parseFloat(startTime);
      var initialScale = obj.initialScale;
      var initialRotate = obj.initialRotate;
      var initialOpacity = obj.initialOpacity;
      obj.setDuration(0);
      
      obj.setInitialScale(initialScale);
      obj.setInitialRotate(initialRotate);
      obj.setInitialOpacity(initialOpacity);
      setTimeout(bump,startTime+duration+100,false)
      setTimeout(go,startTime+200,false);

      function bump() {
        PASS.classList.add('bump');
        setTimeout(function(){
          PASS.classList.remove('bump');
        },100);
      }

      function go() {
        obj.setDuration(duration);
        obj.setInitialScale(obj.endScale);
        obj.setInitialRotate(obj.endRotate);
        obj.setInitialOpacity(obj.endOpacity);

        var resetValues = function() {
          obj.resetScale(initialScale);
          obj.resetRotate(initialRotate);
          obj.resetOpacity(initialOpacity);
          obj.isAnimated = false;
          obj.element.removeEventListener('webkitTransitionEnd',resetValues, false );
        }

        obj.element.addEventListener('webkitTransitionEnd',resetValues,false);
      }
    }
  }

  var PASS = document.getElementById('pass');

  var arrayElements = [new Stamp(document.getElementById('houston_stamp'),1),new Stamp(document.getElementById('phoenix_stamp'),2)];

  saveState = function() {
    window.location.search = '';
    var str = '';

    for (var i = 0; i < arrayElements.length; i++) {
      var obj = arrayElements[i];
      var object = {
        delay: obj.getDelayFromParameter(),
        duration: obj.getDurationFromParameter(),
        definedTiming: obj.getDefinedTimingFromParameter(),
        customTiming: obj.getCustomTimingFromParameter(),
        initialScale: obj.getInitialScaleFromParameter(),
        initialRotate: obj.getInitialRotateFromParameter(),
        initialOpacity: obj.getInitialOpacityFromParameter(),
        endScale: obj.getEndScaleFromParameter(),
        endRotate: obj.getEndRotateFromParameter(),
        endOpacity: obj.getEndOpacityFromParameter()
      }

      console.log(object.initialScale);

      var index = i+1;
      for (var prop in object) {
        str += (prop+index+'='+object[prop]) + '&';
      }
    }
  
    window.location.search = str;
  }


  /*** DATA-GUI ***/
  var PassStamps = function(obj) {
    this.delay = obj.getDelayFromParameter();
    this.duration = obj.getDurationFromParameter();
    this.definedTiming = obj.getDefinedTimingFromParameter();
    this.testStamp = function(){};
    this.initialScale = obj.getInitialScaleFromParameter();
    this.endScale = obj.getEndScaleFromParameter();
    this.initialRotate = obj.getInitialRotateFromParameter();
    this.endRotate = obj.getEndRotateFromParameter();
    this.initialOpacity = obj.getInitialOpacityFromParameter();
    this.endOpacity = obj.getEndOpacityFromParameter();
    this.obj = obj;


    this.TESTALL = function() {
      saveState();
    };
  };
  
  var gui = new dat.GUI();
  
  for(var i = 0; i < arrayElements.length; i++) {
    var passStamps = new PassStamps(arrayElements[i]);
    var obj = arrayElements[i].element;

    var f = gui.addFolder(obj.getAttribute('alt'));
    var initialFolder = f.addFolder('Initial');
    var endFolder = f.addFolder('End');
    var Properties = f.addFolder('Properties');

    var delay = Properties.add(passStamps, 'delay', 0, 3000);

    var duration = Properties.add(passStamps, 'duration', 0, 3000);
    
    var definedTiming = Properties.add(passStamps, 'definedTiming', 
                   propDefTiming);

    var definedTimingParameter = propDefTiming[arrayElements[i].getDefinedTimingFromParameter()];
    definedTimingParameter = !!definedTimingParameter ? definedTimingParameter : 'linear';
    definedTiming.setValue(definedTimingParameter);

    var initialScale = initialFolder.add(passStamps, 'initialScale', 0, 4);
    var endScale = endFolder.add(passStamps, 'endScale', 0, 4);

    var initialRotate = initialFolder.add(passStamps, 'initialRotate', -180, 180);
    var endRotate = endFolder.add(passStamps, 'endRotate', -180, 180);

    var initialOpacity = initialFolder.add(passStamps, 'initialOpacity', 0, 1);
    var endOpacity = endFolder.add(passStamps, 'endOpacity', 0, 1);

    var test = f.add(passStamps,'testStamp');

    //init
    passStamps.obj.setDelay(arrayElements[i].getDelayFromParameter());
    passStamps.obj.setDuration(arrayElements[i].getDurationFromParameter());
    passStamps.obj.setTiming(definedTimingParameter);
    passStamps.obj.setInitialRotate(arrayElements[i].getInitialRotateFromParameter());
    passStamps.obj.setEndRotate(arrayElements[i].getEndRotateFromParameter());
    passStamps.obj.setInitialScale(arrayElements[i].getInitialScaleFromParameter());
    passStamps.obj.setEndScale(arrayElements[i].getEndScaleFromParameter());
    passStamps.obj.setInitialOpacity(arrayElements[i].getInitialOpacityFromParameter());
    passStamps.obj.setEndOpacity(arrayElements[i].getEndOpacityFromParameter());
    passStamps.obj.start();
    //end init

    test.onChange(function(){
      if (!!!this.object.obj.isAnimated){
        this.object.obj.start();
      }  
    });

    initialRotate.onChange(function(value){
      this.object.obj.setInitialRotate(value);
    });

    endRotate.onChange(function(value){
      this.object.obj.setEndRotate(value);
    });

    initialScale.onChange(function(value){
      this.object.obj.setInitialScale(value);
    });

    endScale.onChange(function(value){
      this.object.obj.setEndScale(value);
    });

    initialOpacity.onChange(function(value){
      this.object.obj.setInitialOpacity(value);
    });

    endOpacity.onChange(function(value){
      this.object.obj.setEndOpacity(value);
    });

    // customTiming.onChange(function(value){
    //   // CHANGE CUSTOM TIMING OBJECT
    //   var regex = /([\d.]+,\s*){3}[\d.]+/gi;
    //   var match = regex.exec(value);
    //   if (!!match) {
    //     var value = match[0];
    //     var cubicB = 'cubic-bezier';
    //     value = value.indexOf(cubicB) !== -1 ? cubicB +'(' + value + ')' : value;
    //     this.object.obj.setTiming(value);
    //   }
    // });

    definedTiming.onChange(function(value){
      this.object.obj.setTiming(value);
    });

    duration.onChange(function(value){
      this.object.obj.setDuration(value);
    });

    delay.onChange(function(value){
      this.object.obj.setDelay(value);
    });

  }
  gui.add(passStamps,'TESTALL');
}